import LolModel from './Model';

function LOLLoader() {
}

LOLLoader.prototype.load = function (url, options) {
    if (!Array.isArray(url) || url.length < 3) {
        console.warn(`LOLLoader: url must be an array, and contains .lmesh,.lanim and .png three urls.`);
        return new Promise(resolve => {
            resolve(null);
        });
    }

    let lmesh = url.filter(n => n.endsWith('.lmesh'))[0];
    let lanim = url.filter(n => n.endsWith('.lanim'))[0];
    let png = url.filter(n => n.endsWith('.png'))[0];

    if (lmesh === undefined) {
        console.warn(`LOLLoader: url doesn't contain .lmesh url.`);
        return new Promise(resolve => {
            resolve(null);
        });
    }

    if (lanim === undefined) {
        console.warn(`LOLLoader: url doesn't contain .lanim url.`);
        return new Promise(resolve => {
            resolve(null);
        });
    }

    if (png === undefined) {
        console.warn(`LOLLoader: url doesn't contain .png url.`);
        return new Promise(resolve => {
            resolve(null);
        });
    }

    let fileName = lmesh.split('/')[lmesh.split('/').length - 1];
    let fileNameNoExt = fileName.split('.')[0];
    let champion = fileNameNoExt.split('_')[0];
    let skin = fileNameNoExt.split('_')[1];

    return new Promise(resolve => {
        let model = new LolModel({
            champion: champion,
            skin: parseInt(skin),
            meshUrl: lmesh,
            animUrl: lanim,
            textureUrl: png
        });
        model.load();
        model.on('load.LOLLoader', () => {
            let geometry = model.geometry;
            let material = model.material;
            let mesh = new THREE.Mesh(geometry, material);
            model.mesh = mesh;
            resolve(model);
        });
    });
};

window.LOLLoader = LOLLoader;